<template>
  <dnd-preview>
    <img :src="imgurl" alt="" :style="imgStyle" />
  </dnd-preview>
  <DragPreviewImage :connect="preview" :src="imgempty" />
  <div :ref="drag">
    <div ref="myDrag" class="box-img">
      <img
        :src="dragImg"
        alt=""
        draggable="false"
        :class="
          props.record.isPublished === 1 || props.record.editing
            ? 'img-cursor-default'
            : 'img-cursor-pointer'
        "
      />
    </div>
  </div>
</template>

<script setup>
import { DragPreviewImage, useDrag, useDrop } from 'vue3-dnd'
import DndPreview from 'vue-dnd-preview'
import { onMounted, ref, watch, computed, unref, reactive, nextTick } from 'vue'
import html2canvas from 'html2canvas'
import { leftAssociative, tryCatch } from 'mammoth/mammoth.browser'
import { toRefs } from '@vueuse/core'
import dragImg from '@/assets/images/drag.png'
import { message } from 'ant-design-vue'
import {
  useDataSource,
  useExpandedKeys,
  useDataSourceManager,
} from './provide-context.js'
import { updateOrder } from '@/api/tag.js'
// 接收父组件传递的 props
const props = defineProps({
  record: {
    type: Object,
    required: true,
  },
})

let dataSource = useDataSource()
let expandedKeys = useExpandedKeys()
let { update } = useDataSourceManager()
let isDragStart = ref(true)
const myDrag = ref(null)
const imgurl = ref('')

const dragFeedback = ref(null)
const dragFeedbackDashed = ref(null)

const imgempty =
  ''

const imgStyle = reactive({
  width: '80%',
  transform: '',
})
const rectX = ref()

const box = ref()
const canvasSnapshot = ref(null)
const [collect, drag, preview] = useDrag(() => ({
  type: 'box',
  item: () => {
    return props.record
  },
  collect: monitor => ({
    isDragging: monitor.isDragging(),
  }),
  canDrag: () => {
    const hasTarget = expandedKeys.value.includes(props.record.tagId)
    if (props.record.type === 0 && hasTarget) {
      message.error('已展开标签组不能进行排序!')
      return false
    } else if (props.record.isPublished === 1) {
      message.error('已发布标签组/标签不能进行排序!')
      return false
    } else if (props.record.editing) {
      message.error('在编辑中的标签组/标签不能进行排序!')
      return false
    } else {
      return true
    }
  },
  end: async (draggedItem, monitor) => {
    imgurl.value = null
    imgStyle.transform = null
    canvasSnapshot.value = null
    // overlayInfo.value = null
    // 移除添加的div
    if (dragFeedback.value || dragFeedbackDashed.value) {
      // 从 body 中移除覆盖的 div
      document.body.removeChild(dragFeedback.value)
      dragFeedback.value = null
      document.body.removeChild(dragFeedbackDashed.value)
      dragFeedbackDashed.value = null
    }
    const dropResult = monitor.getDropResult()
    if (dropResult) {
      try {
        let params = {
          tagId: props.record.tagId,
          newOrderBy: dropResult.orderBy,
          newParentId: dropResult.parentId,
          newTagId: dropResult.tagId,
        }
        await updateOrder(params)
        await update()
        if (dropResult.type === 0 && props.record.type === 1) {
          expandedKeys.value = [...expandedKeys.value, dropResult.tagId]
        }
      } catch (e) {
        message.error('排序失败!')
      }
    }
  },
}))
const isDragging = computed(() => unref(collect).isDragging)

watch(
  isDragging,
  async (newIsDragging, oldIsDragging) => {
    if (newIsDragging === true && oldIsDragging === false) {
      //tr
      const rect =
        myDrag.value.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getBoundingClientRect()
      // 创建覆盖的 div 元素
      const feedbackDiv = document.createElement('div')
      feedbackDiv.style.position = 'absolute'
      feedbackDiv.style.top = rect.top + 'px'
      feedbackDiv.style.left = rect.left + 'px'
      feedbackDiv.style.width = rect.width + 'px'
      feedbackDiv.style.height = rect.height + 'px'
      feedbackDiv.style.backgroundColor = '#fff'
      feedbackDiv.style.zIndex = 999
      const feedbackDivDashed = document.createElement('div')
      feedbackDivDashed.style.position = 'absolute'
      feedbackDivDashed.style.top = rect.top + 'px'
      feedbackDivDashed.style.left = rect.left + 'px'
      feedbackDivDashed.style.width = rect.width + 'px'
      feedbackDivDashed.style.height = rect.height + 'px'
      feedbackDivDashed.style.backgroundColor = 'rgba(61,109,153,0.08)'
      feedbackDivDashed.style.border = '1px dashed #c9c9c9'
      feedbackDivDashed.style.zIndex = 9999
      // 将 div 追加到 body 中
      document.body.appendChild(feedbackDiv)
      document.body.appendChild(feedbackDivDashed)
      dragFeedback.value = feedbackDiv
      dragFeedbackDashed.value = feedbackDivDashed
      //drag对象
      const childRect =
        myDrag.value.parentNode.parentNode.parentNode.parentNode.parentNode.getBoundingClientRect()
      rectX.value = childRect.x - rect.x
      imgStyle.transform = `translate(${-rectX.value}px,${-rect.height / 2}px)`

      const trHtml =
        myDrag.value.parentNode.parentNode.parentNode.parentNode.parentNode
          .parentNode
      canvasSnapshot.value = await html2canvas(trHtml)
      imgurl.value = canvasSnapshot.value.toDataURL()
    }
  },
  { immediate: false },
)
</script>

<style lang="less" scoped>
.box-img {
  display: flex;
  align-items: center;
  width: 20px;
}
.img-cursor-default {
  cursor: default;
}
/* 指定表格内的图片 */
.img-cursor-pointer {
  cursor: pointer !important;
}
</style>
